#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@File ：AddressLogic.py
@Author ：zqy
@Email : zqingy@work@163.com 
@note: 
"""
from flask import g

from application.Parser.AddressParser import AddressValidator
from application.enumeration.StatusCodeEnum import StatusCodeEnum
from application.exception.BasicException import BasicException
from application.logic import BaseLogic
from application.mapper.AddressMapper import AddressMapper
from application.model.OrderModel import Address
from application.util.MysqlUtil import mysql_session


class AddressLogic(BaseLogic):
    """
    购物车逻辑类
    """
    model: Address = Address  # 定义模型
    mapper: AddressMapper = AddressMapper  # 定义mapper
    validator: AddressValidator = AddressValidator

    @classmethod
    def get_by_user_id(cls, user_id):
        """
        获取用户地址
        :param user_id:
        :return:
        """
        return [i.to_dict() for i in cls.mapper.get_by_user_id(user_id)]

    @classmethod
    def add(cls, data):
        data["user_id"] = g.user.id
        if data.get("is_default") is True:
            _ids = [_id for _id, *_ in cls.model.query.filter(
                cls.model.user_id == g.user.id,
                cls.model.is_default == True
            ).with_entities(cls.model.id).all()]
            if not cls.mapper.update_by_ids(_ids, {"is_default": False}):
                raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="更新失败")
        address_model = cls.model(**data)

        if not cls.mapper.insert(address_model):
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="添加失败")

    @classmethod
    def update_by_id(cls, _id, data):
        """
        更新地址
        :param id:
        :param data:
        :return:
        """
        address_model = cls.model.get_by_id(_id)
        if not address_model:
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="地址不存在")
        if address_model.user_id != g.user.id:
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="地址不存在")
        if not cls.mapper.update_by_id(_id, data):
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="更新失败")

    @classmethod
    def delete_by_ids(cls, _id):
        """
        删除地址
        :param id:
        :return:
        """
        address_model = cls.model.get_by_id(_id)
        if not address_model:
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="地址不存在")
        if address_model.user_id != g.user.id:
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="地址不存在")
        if not cls.mapper.delete_by_ids(_id):
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="删除失败")

    @classmethod
    def set_default_address(cls, _id):
        """
        设置默认地址
        :param id:
        :return:
        """
        address_model = cls.model.get_by_id(_id)
        if not address_model:
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="地址不存在")
        if address_model.user_id != g.user.id:
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="地址不存在")
        _ids = [_id for _id, *_ in cls.model.query.filter(
            cls.model.user_id == g.user.id,
            cls.model.is_default == True,
            cls.model.id != _id
        ).with_entities(cls.model.id).all()]
        if not cls.mapper.update_by_ids(_ids, {"is_default": False}):
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="更新失败")

        address_model.is_default = True
        try:
            mysql_session.add(address_model)
            mysql_session.commit()
        except Exception as e:
            mysql_session.rollback()
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="更新失败")
